package com.bh.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bh.common.annotation.DataDictClass;
import com.bh.common.constant.Entity;
import com.bh.common.exception.ServiceException;
import com.bh.common.exception.base.BaseException;
import com.bh.common.utils.DateUtils;
import com.bh.common.utils.SecurityUtils;
import com.bh.common.utils.StringUtils;
import com.bh.extend.domain.JcCustomer;
import com.bh.extend.domain.JcReceivingParty;
import com.bh.extend.service.IJcCustomerService;
import com.bh.extend.service.IJcReceivingPartyService;
import com.bh.kysys.domain.JcZone;
import com.bh.kysys.mapper.JcZoneMapper;
import com.bh.kysys.service.IJcZoneService;
import com.bh.order.domain.JcLedReceivingParty;
import com.bh.order.domain.JcOrderReceivingParty;
import com.bh.order.domain.JcServerZone;
import com.bh.order.mapper.JcServerZoneMapper;
import com.bh.order.service.IJcLedReceivingpartyService;
import com.bh.order.service.IJcOrderReceivingPartyService;
import com.bh.order.service.IJcServerZoneService;
import com.bh.order.vo.JcServerZoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 服务区域Service业务层处理
 *
 * @author slx
 * @date 2023-04-24
 */

@Service
public class JcServerZoneServiceImpl extends ServiceImpl<JcServerZoneMapper, JcServerZone> implements IJcServerZoneService {
    @Autowired
    private JcServerZoneMapper jcServerZoneMapper;
    @Autowired
    private IJcZoneService jcZoneService;
    @Autowired
    private JcZoneMapper jcZoneMapper;
    @Autowired
    private IJcCustomerService jcCustomerService;
    @Autowired
    private IJcLedReceivingpartyService jcLedReceivingpartyService;
    @Autowired
    private IJcOrderReceivingPartyService jcOrderReceivingPartyService;
    @Autowired
    private IJcReceivingPartyService jcReceivingPartyService;


    /**
     * 查询服务区域
     *
     * @param id 服务区域主键
     * @return 服务区域
     */
    @DataDictClass
    @Override
    public JcServerZone selectJcServerZoneById(Long id) {
        return jcServerZoneMapper.selectById(id);
    }

    /**
     * 查询服务区域列表
     *
     * @param jcServerZone 服务区域
     * @return 服务区域
     */
    @DataDictClass
    @Override
    public List<JcServerZone> selectJcServerZoneList(JcServerZone jcServerZone) {
        return jcServerZoneMapper.selectJcServerZoneList(jcServerZone);
    }

    @Override
    public String importData(List<JcServerZone> data, String operName) {
        if (StringUtils.isNull(data) || data.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (JcServerZone serverZone : data) {
            try {
                // 验证是否存在这个用户
                JcServerZone zone = jcServerZoneMapper.selectById(serverZone.getId());
                if (StringUtils.isNull(zone)) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、配送时效对应的服务区域未找到已存在");
                } else {
                    jcServerZoneMapper.updateById(zone);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、配送时效导入成功");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、配送时效导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
                e.printStackTrace();
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @DataDictClass
    @Override
    public List<JcServerZone> selectJcServerZoneByOrgId(Long orgId) {
        return jcServerZoneMapper.selectJcServerZoneByOrgId(orgId);
    }

    /**
     * 新增服务区域
     *
     * @param jcServerZone 服务区域
     * @return 结果
     */
    @Override
    public int insertJcServerZone(JcServerZone jcServerZone) {
        JcServerZone oldParam = new JcServerZone();
        if (StringUtils.isBlank(jcServerZone.getJcOrganizationId())) {
            oldParam.setJcOrganizationId(SecurityUtils.getOrgId());
        } else {
            oldParam.setJcOrganizationId(jcServerZone.getJcOrganizationId());
        }
        oldParam.setJcZoneId(jcServerZone.getJcZoneId());
        List<JcServerZone> olds = jcServerZoneMapper.selectJcServerZoneList(oldParam);
        if (olds != null && olds.size() > 0) {
            throw new BaseException("服务区域已经存在！");
        }
        jcServerZone.setType(0);
        jcServerZone.setStatus(Entity.ACTIVE);
        jcServerZone.setCreateTime(DateUtils.getNowDate());
        jcServerZone.setCreateName(SecurityUtils.getUsername());
        return jcServerZoneMapper.insert(jcServerZone);
    }


    @Override
    public Long insertJcServerZoneByAddress(JcServerZoneVo serverZoneVo) {
        // 处理地址
        String zoneNames = serverZoneVo.getZones().trim().replaceAll("，", ",");
        // 去除开头和结尾的逗号
        zoneNames = zoneNames.replaceAll("^,|,$", "");
        Map<String, String> zoneMap = jcZoneService.selectJcZoneByZoneNames(zoneNames);
        if (zoneMap == null || zoneMap.size() == 0) {
            throw new BaseException("地址识别失败！");
        }
        long lastZoneId = Long.parseLong(zoneMap.get("lastZoneId"));
        // 地址识别以后按照顺序去查询
        JcServerZone olds = jcServerZoneMapper.selectJcServerZoneByZoneId(lastZoneId, serverZoneVo.getOrgId());
        if (olds == null) {
            String fullZoneId = zoneMap.get("fullZoneId");
            String fullZoneName = zoneMap.get("fullZoneName");
            JcServerZone serverZone = new JcServerZone();
            serverZone.setType(0);
            serverZone.setJcOrganizationId(serverZoneVo.getOrgId());
            serverZone.setJcZones(fullZoneId);
            serverZone.setJcZoneId(lastZoneId);
            serverZone.setName(fullZoneName);
            serverZone.setStatus(Entity.ACTIVE);
            serverZone.setCreateTime(DateUtils.getNowDate());
            serverZone.setCreateName(SecurityUtils.getUsername());
            jcServerZoneMapper.insert(serverZone);
            return serverZone.getId();
        } else {
            return olds.getId();
        }
    }

    @Override
    public JcServerZone selectJcServerZoneByName(String name, Long orgId) {
        if (StringUtils.isEmpty(name)) {
            return null;
        }
        // 处理地址, 去除开头和结尾的逗号
        name = name.trim().replaceAll("，", ",").replaceAll("^,|,$", "");
        Map<String, String> zoneMap = jcZoneService.selectJcZoneByZoneNames(name);
        if (zoneMap == null || zoneMap.size() == 0) {
            throw new BaseException("地址识别失败！");
        }
        long lastZoneId = Long.parseLong(zoneMap.get("lastZoneId"));
        // 地址识别以后按照顺序去查询
        return jcServerZoneMapper.selectJcServerZoneByZoneId(lastZoneId, orgId);
    }

    /**
     * 修改服务区域
     *
     * @param jcServerZone 服务区域
     * @return 结果
     */
    @Override
    public int updateJcServerZone(JcServerZone jcServerZone) {
        JcServerZone oldParam = new JcServerZone();
        if (StringUtils.isEmpty(jcServerZone.getJcOrganizationId())) {
            oldParam.setJcOrganizationId(SecurityUtils.getOrgId());
        } else {
            oldParam.setJcOrganizationId(jcServerZone.getJcOrganizationId());
        }
        oldParam.setJcZoneId(jcServerZone.getJcZoneId());
        List<JcServerZone> oldList = jcServerZoneMapper.selectJcServerZoneList(oldParam);
        if (oldList != null && oldList.size() > 0 && !oldList.get(0).getId().equals(jcServerZone.getId())) {
            throw new BaseException("服务区域已经存在！");
        }
        jcServerZone.setModifyName(SecurityUtils.getUsername());
        jcServerZone.setModifyTime(DateUtils.getNowDate());
        return jcServerZoneMapper.updateById(jcServerZone);
    }

    /**
     * 批量删除服务区域
     *
     * @param ids 需要删除的服务区域主键
     * @return 结果
     */
    @Override
    public int deleteJcServerZoneByIds(Long[] ids) {
        return jcServerZoneMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除服务区域信息
     *
     * @param id 服务区域主键
     * @return 结果
     */
    @Override
    public int deleteJcServerZoneById(Long id) {
        return jcServerZoneMapper.deleteById(id);
    }

    @Override
    public BigDecimal getZonePrice(String zoneId) {

        return null;
    }
}
